﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI.WebControls;
using Core.Authenticated;
using Core.Library;
using DataObject;
using DataObject.Category;
using DataObject.Product;

namespace CMS.Controls.Product
{
    public partial class ProductManager : AuthenticatedControl
    {
        protected string Url;
        protected string Keyword;
        protected string CurrentKeyword = string.Empty;
        protected int CategoryId;
        protected new int Status;
        protected int Type;
        protected int PageSize;
        protected int PageIndex;
        protected int Draft;
        protected int Published;
        protected int Highlight;

        protected void Page_Load(object sender, EventArgs e)
        {
            CategoryId  = Utils.GetIdFromRequestString(Utils.CategoryId, 0);
            Status      = Utils.GetIdFromRequestString(Utils.Status, 0);
            Type        = Utils.GetIdFromRequestString(Utils.TypeId, 0);
            PageIndex   = Utils.GetIdFromRequestString(Utils.PageIndex, SettingValues.PageIndex);
            PageSize    = Utils.GetIdFromRequestString(Utils.PageSize, ConvertUtility.ToInt32(ddlPageSize.SelectedValue));            
            Keyword     = Utils.GetIdFromRequestString(Utils.Keyword, string.Empty);
            Url         = HttpUtility.UrlEncode(Request.Url.ToString());

            if (!IsPostBack)
            {
                if (!string.IsNullOrEmpty(Keyword))
                {
                    Keyword         = HttpUtility.UrlDecode(Keyword);
                    txtKeyword.Text = Keyword;
                }

                ListTreeCategory();
                ListData();
            }
        }

        #region Statistics

        private void GetStatistics()
        {
            Highlight   = ProductController.Product_GetStatistic((int)ProductStatus.Highlight);
            Published   = ProductController.Product_GetStatistic((int)ProductStatus.IsPublished);
            Draft       = ProductController.Product_GetStatistic((int)ProductStatus.IsDraft);
        }

        #endregion

        private void ListTreeCategory()
        {
            var categories = new List<CategoryObject>();
            CategoryController.GetListTree(categories, (int)CategoryType.Product, 0, Constants.PARENT_ROOT);

            if (categories.Count > 0)
            {
                ddlCategory.DataSource = categories;
                ddlCategory.DataBind();
                ddlCategory.Items.Insert(0, new ListItem("-- Danh mục --", "0"));
            }
        }

        private void ListData()
        {
            var totalRecords = 0;

            var products = ProductController.Product_ListPaginationByCategory(Keyword, CategoryId, Status, Type, PageIndex, PageSize, ref totalRecords);
            lvList.DataSource = products;
            lvList.DataBind();            

            ltPager.Text = PagerUtility.PageLinks(PageIndex, PageSize, totalRecords, 5,
                                                    UrlHelpers.PaginationLinkProduct(Keyword, CategoryId, Status, Type, "{0}", PageSize));

            ddlCategory.SelectedValue = CategoryId.ToString();
            ddlStatus.SelectedValue   = Status.ToString();
            ddlType.SelectedValue     = Type.ToString();

            GetStatistics();
        }

        private void UpdateStatus(int targetStatus)
        {
            ltMessage.Text = string.Empty;
            var count = 0;
            foreach (ListViewDataItem lvi in lvList.Items)
            {
                var cbItem = (CheckBox)lvi.FindControl("cbItem");
                if (cbItem == null || !cbItem.Checked) continue;

                count++;
                var id = ConvertUtility.ToInt32(lvList.DataKeys[lvi.DisplayIndex].Value);
                if (id > 0)
                {
                    var o = ProductController.Product_GetById(id);
                    if (o != null)
                        ProductController.Product_Update_Status(id, targetStatus);
                }
            }

            if (count == 0)
                ltMessage.Text = MessageUtility.ShowMessage(string.Empty, "Bạn chưa chọn sản phẩm nào.", MessageType.Warning);

            ListData();
            GetStatistics();
        }

        protected void BtnPublished(object sender, EventArgs e)
        {
            UpdateStatus((int)ProductStatus.IsPublished);
        }

        protected void BtnHighlight(object sender, EventArgs e)
        {
            UpdateStatus((int)ProductStatus.Highlight);
        }

        protected void BtnCreate(object sender, EventArgs e)
        {
            Response.Redirect(UrlHelpers.CreateProduct(HttpUtility.UrlEncode(Request.Url.ToString())));
        }

        protected void BtnSearch(object sender, EventArgs e)
        {
            RedirectLink();
        }        

        protected void ddlCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            RedirectLink();
        }

        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            RedirectLink();
        }

        protected void ddlStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            RedirectLink();
        }

        protected void ddlType_SelectedIndexChanged(object sender, EventArgs e)
        {
            RedirectLink();
        }

        public void RedirectLink()
        {
            var keyword     = HttpUtility.UrlEncode(txtKeyword.Text);
            var categoryId  = ConvertUtility.ToInt32(ddlCategory.SelectedValue);
            var status      = ConvertUtility.ToInt32(ddlStatus.SelectedValue);
            var type        = ConvertUtility.ToInt32(ddlType.SelectedValue);
            var pageSize    = ConvertUtility.ToInt32(ddlPageSize.SelectedValue);

            Response.Redirect(UrlHelpers.PaginationLinkProduct(keyword, categoryId, status, type, SettingValues.PageIndex.ToString(), pageSize));
        }

        protected void lvList_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            var dataItem = (ListViewDataItem)e.Item;
            var id = ConvertUtility.ToInt32(lvList.DataKeys[dataItem.DisplayIndex].Value);

            if (id > 0)
            {                
                if (string.Equals(e.CommandName, "DeleteProduct"))
                {
                    try
                    {
                        ProductController.Product_Delete(id);
                        ltMessage.Text = MessageUtility.ShowMessage(string.Empty, "Xóa dữ liệu thành công", MessageType.Success);
                        ListData();
                    }
                    catch
                    {
                        ltMessage.Text = MessageUtility.ShowMessage(string.Empty, "Bạn cần xóa các thông tin liên quan đến sản phẩm. Trước khi xóa sản phẩm này.", MessageType.Information);
                    }
                }
            }
        }

        protected void lvList_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                var ltStatus = (Literal) e.Item.FindControl("ltStatus");
                var status = ConvertUtility.ToInt32(((HiddenField)e.Item.FindControl("hfStatus")).Value);

                switch (status)
                {
                    case (int)ProductStatus.Highlight:
                        ltStatus.Text = "<a class=\"btn14 topDir\" title=\"Nổi bật\"><img src=\"/images/icons/color/pin.png\" alt=\"\"/></a>";
                        break;
                    case (int)ProductStatus.IsPublished:
                        ltStatus.Text = "<a class=\"btn14 topDir\" title=\"Xuất bản\"><img src=\"/images/icons/color/paper-clip.png\" alt=\"\"/></a>";
                        break;
                    case (int)ProductStatus.IsDraft:
                        ltStatus.Text = "<a class=\"btn14 topDir\" title=\"Lưu tạm\"><img src=\"/images/icons/color/notebook.png\" alt=\"\"/></a>";
                        break;
                }
            }
        }
    }
}